package com.gopay.common.util.cbrmb;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.ArrayUtils;

/**
 * 
 * @ClassName: MsgUtils 
 * @Description: 信息处理工具类 
 * @author gd.cui
 * @date 2016年6月29日 上午11:22:31 ww.gopay.com.cn Inc.All rights reserved.
 */
public class MsgUtils {

	private static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

	private static final String YYYYMMDD = "yyyyMMdd";

	private static final String HHMMSS = "HHmmss";

	/**
	 * 转换字符串去指定长度的字节数组 字节数组长度不能小于字符串转换后的长度
	 * 
	 * @param data
	 * @param charsetName
	 * @param length
	 * @return
	 */
	public static byte[] convertString2Bytes(String data, String charsetName, int length) {
		try {
			byte[] bytes = data.getBytes(charsetName);
			int copyLength = bytes.length;
			byte[] result = new byte[length];
			copyBytes(bytes, result, 1, copyLength, 1);
			return result;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return new byte[length];
	}

	public static byte[] convertString2Bytes(String data, int length) {
		return convertString2Bytes(data, "UTF-8", length);
	}

	/**
	 * 复制字节
	 * 
	 * @param source
	 * @param dest
	 * @param sourceFrom
	 *            从1开始
	 * @param copyLength
	 *            需要复制的长度
	 * @param destFrom
	 *            从1开始
	 */
	public static void copyBytes(byte[] source, byte[] dest, int sourceFrom, int copyLength, int destFrom) {
		sourceFrom = sourceFrom - 1;
		destFrom = destFrom - 1;
		for (int i = destFrom; i < destFrom + copyLength; i++) {
			dest[i] = source[sourceFrom++];
		}
	}

	public static byte[] mergeBytes(byte[]... bytes) {
		byte[] temp = new byte[0];
		for (int i = 0; i < bytes.length; i++) {
			temp = ArrayUtils.addAll(temp, bytes[i]);
		}
		return temp;
	}

	public static String date2StrYYYYMMDD(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(YYYYMMDD);
		return sdf.format(date);
	}

	public static String date2StrHHMMSS(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(HHMMSS);
		return sdf.format(date);
	}

	public static String date2StrYYYYMMDDHHMMSS(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(YYYYMMDDHHMMSS);
		return sdf.format(date);
	}

	private static long FILE_MIN_SEQ = 0;

	private static long FILE_MAX_SEQ = 999;

	private static long FILE_CUR_SEQ = FILE_MIN_SEQ;

	public static synchronized String getFileSeq() {
		if (FILE_CUR_SEQ == FILE_MAX_SEQ) {
			FILE_CUR_SEQ = FILE_MIN_SEQ;
		}
		return String.format("%03d", FILE_CUR_SEQ++);
	}
	
	private static long MESSAGE_MIN_SEQ = 0;

	private static long MESSAGE_MAX_SEQ = 999;

	private static long MESSAGE_CUR_SEQ = MESSAGE_MIN_SEQ;

	public static synchronized String getMessageSeq() {
		if (MESSAGE_CUR_SEQ == MESSAGE_MAX_SEQ) {
			MESSAGE_CUR_SEQ = MESSAGE_MIN_SEQ;
		}
		return String.format("%03d", MESSAGE_CUR_SEQ++);
	}
	

}
